package com.building.hcrm.common;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.ref.WeakReference;
import java.net.URLEncoder;

import com.building.hcrm.R;
import com.building.hcrm.R.string;
import com.building.hcrm.model.ApkFileInfo;
import com.building.hcrm.model.DownloadUpdateFileQuery;
import com.building.hcrm.wcf.UpdateServiceProxy;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;


public class UpdateManager {

	private final String LTAG = UpdateManager.class.getSimpleName();
	public static String TIME_OUT = "time out";
	private ApkFileInfo apkInfo;
	/* 下载保存路径 */
	private String mSavePath;
	/* 记录进度条数量 */
	private int progress;
	/* 是否取消更新 */
	private boolean cancelUpdate = false;

	private Context mContext;

	/**
	 * 文件总大小
	 */
	private int offset = 0;
	/**
	 * 每个下载包的大小
	 */
	private final int PACK_SIZE = 102400;

	/* 更新进度条 */
	private ProgressBar mProgress;
	private Dialog mDownloadDialog;
	/**
	 * 主界面的handler
	 */
	private Handler ohandler;
	private UpdateHandler mHandler = new UpdateHandler(this);

	private static class UpdateHandler extends Handler {
		WeakReference<UpdateManager> mManager;

		UpdateHandler(UpdateManager um) {
			mManager = new WeakReference<UpdateManager>(um);
		}

		public void handleMessage(Message msg) {
			final UpdateManager updateManager = mManager.get();
			switch (msg.what) {
			// 正在下载
			case ComConst.DOWNLOAD:
				// 设置进度条位置
				updateManager.mProgress.setProgress(updateManager.progress);
				break;
			case ComConst.DOWNLOAD_FINISH: {
				// 安装文件
				updateManager.installApk();
			}
				break;
			case ComConst.DOWNLOAD_ERROR: {
				// 安装文件
				updateManager.showTip("下载出错");
			}
				break;
			default:
				break;
			}
		};
	};

	public UpdateManager(Context context, Handler _handler) {
		this.mContext = context;
		ohandler = _handler;
	}

	/**
	 * 检测软件更新
	 */
	public void checkUpdate() {
		if (isUpdate()) {
			// 显示提示对话框
			showNoticeDialog();
		} else {
			// Toast.makeText(mContext, "安装文件信息获取失败", Toast.LENGTH_LONG).show();
			// 发消息给Loadding界面，告知更新检测完成
			msgUpdateCheckFinished();
		}
	}

	/**
	 * 其他界面检测软件更新
	 */
	public void otherCheckUpdate() {
		if (isUpdate()) {
			// 显示提示对话框
			showNoticeDialog();
		} else {
			Toast.makeText(mContext,
					mContext.getString(R.string.update_lastet_msg),
					Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 检查软件是否有更新版本
	 * 
	 * @return
	 */
	private boolean isUpdate() {
		// 获取当前软件版本
		String versionCodeInLocal = getVersionCodeInLocal(mContext);
		// 获取服务端的软件版本
		getVersionInfoInServer();

		// 版本判断
		if (apkInfo != null && apkInfo.Version != null) {
			if (versionCodeInLocal != null
					&& versionCodeInLocal.compareTo(apkInfo.Version) != 0) {
				return true;
			}
		}

		return false;
	}

	/**
	 * 获取服务端最新的软件版本信息
	 * 
	 * @return
	 */
	private void getVersionInfoInServer() {
		try {
			apkInfo = UpdateServiceProxy.getInstance(mContext).GetUpdateFileInfo();
		} catch (Exception e) {
			Log.e(LTAG, ComFunc.getExceptionMessage(e));
		}
	}

	/**
	 * 获取本地软件版本号
	 * 
	 * @param context
	 * @return
	 */
	private String getVersionCodeInLocal(Context context) {
		try {
			// 获取本系统版本号 由MAINFAST获取
			PackageInfo packageInfo = mContext.getPackageManager()
					.getPackageInfo("com.building.hcrm",
							PackageManager.GET_META_DATA);

			return packageInfo.versionName;
		} catch (Exception e) {
			Log.e(LTAG,ComFunc.getExceptionMessage(e));
		}
		return null;
	}

	private void showTip(String msg) {
		Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
	}

	/**
	 * 显示软件更新对话框
	 */
	private void showNoticeDialog() {
		// 构造对话框
		if (!((Activity) mContext).isFinishing())
		{
			AlertDialog.Builder builder = new Builder(mContext);
			builder.setTitle(R.string.soft_update_title);
			builder.setMessage(R.string.soft_update_info);
			// 更新
			builder.setPositiveButton(R.string.soft_update_updatebtn, new OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{

					dialog.dismiss();
					// 显示下载对话框
					showDownloadDialog();
				}
			});
			// 稍后更新
			builder.setNegativeButton(R.string.soft_update_later, new OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					dialog.dismiss();
					// 发消息给Loadding界面，告知更新检测完成
					msgUpdateCheckFinished();
				}
			});
			Dialog noticeDialog = builder.create();
			noticeDialog.setCancelable(false);// 禁止返回键关闭
			noticeDialog.show();
		}
	}

	/**
	 * 发消息给Loadding界面，告知更新检测完成
	 */
	private void msgUpdateCheckFinished() {
		Message msg = Message.obtain();
		msg.what = ComConst.UPDATE_FINISH;
		ohandler.sendMessage(msg);
	}

	/**
	 * 显示软件下载对话框
	 */
	private void showDownloadDialog() {
		// 构造软件下载对话框
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle(R.string.soft_updating);
		// 给下载对话框增加进度条
		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.item_update_progress, null);
		mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
		builder.setView(v);
		builder.setPositiveButton(R.string.cancel, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				cancelUpdate = true;
				msgUpdateCheckFinished();
			}
		});
		mDownloadDialog = builder.create();
		mDownloadDialog.setCancelable(false);// 禁止返回键关闭
		mDownloadDialog.show();
		// 下载文件
		downloadApk();
	}

	/**
	 * 下载apk文件
	 */
	private void downloadApk() {
		// 启动新线程下载软件
		new downloadApkThread().start();
	}

	/**
	 * 安装文件下载线程
	 * 
	 * @author coolszy
	 * @date 2012-4-26
	 * @blog http://blog.92coding.com
	 */
	private class downloadApkThread extends Thread {
		@Override
		public void run() {
			try {
				// 判断SD卡是否存在，并且是否具有读写权限
				if (Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {

					// 获得存储卡的路径
					String sdpath = ComFunc.getStorageDirectory() + "/";
					mSavePath = sdpath + "download";
					// 创建写文件的流
					File file = new File(mSavePath);
					// 判断文件目录是否存在
					if (!file.exists()) {
						file.mkdir();
					}
					File apkFile = new File(mSavePath, apkInfo.FileName);
					FileOutputStream fos = new FileOutputStream(apkFile);

					while (offset < apkInfo.FileSize && !cancelUpdate) {
						// 从服务器下载文件
						DownloadUpdateFileQuery qry = new DownloadUpdateFileQuery();
						qry.FileName = apkInfo.FileName;
						qry.PackSize = PACK_SIZE;
						qry.Offset = offset;

						String strReturn = UpdateServiceProxy.getInstance(
								mContext).DownloadNextPackageFromFile(qry);

						if (strReturn == null || strReturn.length()==0) {
							mHandler.sendEmptyMessage(ComConst.DOWNLOAD_ERROR);

							fos.close();
							// 取消下载对话框显示
							mDownloadDialog.dismiss();
							// 告诉loadding界面
							msgUpdateCheckFinished();
							return;
						}

						byte[] buf = Base64Util.decode(strReturn);
						// 写入文件
						fos.write(buf, 0, buf.length);
						// 更新进度
						offset = offset + buf.length;
						progress = (int) (((float) offset / apkInfo.FileSize) * 100);
						Log.d("debug", "offset: " + offset + "  totalLength: "
								+ apkInfo.FileSize + "  progress: " + progress
								+ "  dowloadSize: " + buf.length);
						mHandler.sendEmptyMessage(ComConst.DOWNLOAD);
						// 提示下载完成
						if (offset >= apkInfo.FileSize) {
							// 下载完成
							mHandler.sendEmptyMessage(ComConst.DOWNLOAD_FINISH);
							break;
						}
					}

					fos.close();
				}
			} catch (Exception e) {
				Log.e(LTAG,ComFunc.getExceptionMessage(e),e);
				mHandler.sendEmptyMessage(ComConst.DOWNLOAD_ERROR);
			}
			// 取消下载对话框显示
			mDownloadDialog.dismiss();
		}
	};

	/**
	 * 安装APK文件
	 */
	private void installApk() {
		File apkfile = new File(mSavePath, apkInfo.FileName);
		if (!apkfile.exists() || cancelUpdate) {
			return;
		}
		// 通过Intent安装APK文件
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setDataAndType(Uri.parse("file://" + apkfile.toString()),
				"application/vnd.android.package-archive");
		mContext.startActivity(intent);
	}
}
